/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package picturemouse;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Duncan
 */
public class MakeBooking extends javax.swing.JFrame {

    public PictureMouse server;
    private Film selectedFilm;
    private Screening selectedScreening;
    private Seat selectedSeat;
    
    /**
     * Creates new form MakeBooking
     * @param server
     */
    public MakeBooking(PictureMouse server) {
        this.server = server;
        initComponents();
        setVisible(true);
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        filmSelector = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        seatingTable = new javax.swing.JTable();
        readReviewsButton = new javax.swing.JButton();
        readSynopsisButton = new javax.swing.JButton();
        watchTrailerButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        submitButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        screeningSelector = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        selectedSeatLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setResizable(false);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 30)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Make Booking");

        cancelButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        filmSelector.setModel(new javax.swing.DefaultComboBoxModel(getFilmList()));
        filmSelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                filmSelectorActionPerformed(evt);
            }
        });

        jLabel1.setText("Film:");

        seatingTable.setAutoCreateRowSorter(true);
        seatingTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        seatingTable.setSelectionBackground(new java.awt.Color(255, 255, 255));
        seatingTable.setSelectionForeground(new java.awt.Color(0, 0, 0));
        seatingTable.getTableHeader().setResizingAllowed(false);
        seatingTable.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(seatingTable);

        readReviewsButton.setText("Read Reviews");
        readReviewsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                readReviewsButtonActionPerformed(evt);
            }
        });

        readSynopsisButton.setText("Read Synopsis");
        readSynopsisButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                readSynopsisButtonActionPerformed(evt);
            }
        });

        watchTrailerButton.setText("Watch Trailer");
        watchTrailerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                watchTrailerButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Seating:");

        submitButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        submitButton.setText("Submit Booking");
        submitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitButtonActionPerformed(evt);
            }
        });

        jLabel3.setText("Screening:");

        screeningSelector.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Please select a film" }));
        screeningSelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                screeningSelectorActionPerformed(evt);
            }
        });

        jLabel5.setText("[  ] = Seat Avaliable");

        jLabel6.setText("[--] = Seat Taken");

        jLabel7.setText("Selected Seat:");

        selectedSeatLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        selectedSeatLabel.setText("None");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(screeningSelector, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(105, 105, 105))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(submitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(24, 24, 24)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(selectedSeatLabel)))
                        .addGap(135, 135, 135))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(readReviewsButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(readSynopsisButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(watchTrailerButton))
                            .addComponent(filmSelector, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(72, 72, 72))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(65, 65, 65)
                                .addComponent(jLabel5)
                                .addGap(38, 38, 38)
                                .addComponent(jLabel6)))
                        .addGap(18, 18, 18))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filmSelector, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(readReviewsButton)
                    .addComponent(readSynopsisButton)
                    .addComponent(watchTrailerButton))
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(screeningSelector, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(selectedSeatLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addComponent(submitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelButton)
                .addGap(19, 19, 19))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //Method to get an array of film names to use with the dropdown list
    private String[] getFilmList() {
        String[] result = new String[server.getFilmArray().length+1];
        result[0] = "Please select a film";
        int i = 1;
        for (Film film : server.getFilmArray()) {
            result[i] = film.getName();
            i++;
        }
        return result;
    }
            
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        //Open home form
        new Home(server);
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void filmSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filmSelectorActionPerformed
        try {
            selectedFilm = server.getFilmByName(filmSelector.getSelectedItem().toString());
        } catch (FilmNotFoundException ex) {return;}
        //The user has selected a film, so populate the screening list with the film's screenings
        ArrayList list = new ArrayList();
        list.add("Please select a screening time and date");
        for (Screening screening : server.getScreeningArray()) {
            if (screening.getFilmName().equals(filmSelector.getSelectedItem())) {
                list.add(screening.getTime());
            }
        }
        if (list.size()==1) list.set(0, "Please select a film.");
        screeningSelector.setModel(new javax.swing.DefaultComboBoxModel(list.toArray(new String[list.size()])));
        
    }//GEN-LAST:event_filmSelectorActionPerformed
    
    private void watchTrailerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_watchTrailerButtonActionPerformed
        try {
            java.awt.Desktop.getDesktop().browse(new URI(selectedFilm.getTrailer()));
        } catch (IOException | URISyntaxException ex) {
            JOptionPane.showMessageDialog(null, "Couldn't open trailer.");
        }
    }//GEN-LAST:event_watchTrailerButtonActionPerformed

    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
        if (selectedScreening==null || selectedSeat==null) {
            JOptionPane.showMessageDialog(null, "Please complete the form.");
            return;
        }
        try {
            server.addBooking(selectedScreening.getID(), server.currentAccount.getCustomerName(), selectedSeat.getID());
        } catch (SeatNotAvaliableException ex) {
            JOptionPane.showMessageDialog(null, "Selected seat is not avaliable.");
            return;
        } catch (ScreeningNotFoundException ex) {
            JOptionPane.showMessageDialog(null, "Couldn't find the selected screening.");
            return;
        }
        JOptionPane.showMessageDialog(null, "Booking successful.");
        new Home(server);
        this.dispose();
    }//GEN-LAST:event_submitButtonActionPerformed

    private void screeningSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_screeningSelectorActionPerformed
        // The user has selected a film and a screening, now show the seating plan
        try {
            selectedScreening = server.getScreeningByTimeAndFilm(screeningSelector.getSelectedItem().toString(), selectedFilm.getName());
        } catch (ScreeningNotFoundException ex) {return;}
        //First find the screen number
        Screening screening = selectedScreening;
        //Next, loop the seats
        HashMap<String, ArrayList<String>> seats = new HashMap<>();
        for (Seat seat : server.getSeatArray()) {
            if (seat.getScreenNum()==screening.getScreenNum()) {
                if (!seats.containsKey(seat.getRow())) {
                    seats.put(seat.getRow(), new ArrayList<String>());
                    seats.get(seat.getRow()).add(seat.getRow());
                }
                if (screening.seatAvaliable(seat.getID(), server)) seats.get(seat.getRow()).add("[  ]");
                else seats.get(seat.getRow()).add("[--]");
            }
        }
        String[][] seatArray = new String[seats.size()][];
        int i = 0;
        int maxRow = 0;
        for (Map.Entry<String, ArrayList<String>> seatRow : seats.entrySet()) {
            seatArray[i] = seatRow.getValue().toArray(new String[seatRow.getValue().size()]);
            maxRow = Math.max(maxRow, seatArray[i].length);
            i++;
        }
        String[] headerArray = new String[maxRow];
        headerArray[0] = "";
        for (i = 1; i<maxRow; i++) {
            headerArray[i] = Integer.toString(i);
        }
        seatingTable.setModel(new javax.swing.table.DefaultTableModel(
            seatArray, headerArray
        ));
        
        
        seatingTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                int row = seatingTable.rowAtPoint(evt.getPoint());
                int col = seatingTable.columnAtPoint(evt.getPoint());
                if (row >= 0 && col >= 1) {
                    int seatNum = Integer.parseInt(seatingTable.getColumnName(col));
                    String seatRow = seatingTable.getValueAt(row, 0).toString();
                    try {
                        Seat seat = server.getSeatByColRow(seatRow, seatNum);
                        if (!selectedScreening.seatAvaliable(seat.getID(), server)) {
                            JOptionPane.showMessageDialog(null, "Seat not avaliable. Please select another.");
                            seatingTable.getSelectionModel().clearSelection();
                            selectedSeat = null;
                            selectedSeatLabel.setText("None");
                            return;
                        }
                        selectedSeat = seat;
                        selectedSeatLabel.setText(seatRow+seatNum);
                    } catch (SeatNotFoundException ex) {return;}
                }
            }
        });

        
    }//GEN-LAST:event_screeningSelectorActionPerformed

    private void readSynopsisButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_readSynopsisButtonActionPerformed
        JOptionPane.showMessageDialog(null, selectedFilm.getSynopsis());
    }//GEN-LAST:event_readSynopsisButtonActionPerformed

    private void readReviewsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_readReviewsButtonActionPerformed
        new ReadReviews(selectedFilm.getName(), server);
    }//GEN-LAST:event_readReviewsButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox filmSelector;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton readReviewsButton;
    private javax.swing.JButton readSynopsisButton;
    private javax.swing.JComboBox screeningSelector;
    private javax.swing.JTable seatingTable;
    private javax.swing.JLabel selectedSeatLabel;
    private javax.swing.JButton submitButton;
    private javax.swing.JButton watchTrailerButton;
    // End of variables declaration//GEN-END:variables
}
